const express = require('express')
const fs = require('fs')
const { createBundleRenderer } = require('vue-server-renderer')
const setupDevServer = require('./build/setup-dev-server')

const server = express()
server.use('/dist', express.static('./dist'))
let renderer
let onReady
const render = async (req, res) => {
    try{
        const html = await renderer.renderToString({
            url: req.url
        })
        res.setHeader('content-type', 'text/html; charset=utf8')
        res.end(html)
    } catch (error) {
        res.status(500).end('服务器异常！')
    }
}
const isProduction = process.env.NODE_ENV === "production"
if(isProduction) {
    const serverBundle = require('./dist/vue-ssr-server-bundle.json')
    const clientManifest = require('./dist/vue-ssr-client-manifest.json')
    const template = fs.readFileSync('./index.template.html', 'utf-8')
    renderer = createBundleRenderer(serverBundle , {
        template,
        clientManifest
    })
} else {
    // 开发模式=》 监视打包构建 =》 重新生成 renderer 渲染器
    onReady = setupDevServer(server, (serverBundle, template, clientManifest) => {
        renderer = createBundleRenderer(serverBundle , {
            template,
            clientManifest
        })
    })
}
// 服务端路由设置成*所有的请求都会经过这里
server.get('*', isProduction ? render : async(req, res) => {
    // DOTO：开发模式下等待 Renderer 渲染完成之后在调用render
    await onReady
    render(req, res)
    
})
server.listen(4000, () => {
    console.log('server running at port 4000')
})
